import { Injectable, Inject } from '@nestjs/common';
import { Repository, DeleteResult, FindOptionsWhere, DeepPartial,FindOneOptions } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
interface Paging {
    search?: any;
    pageSize: number;
    page: number;
}
@Injectable()
export class CrudService<T> {
    constructor(
        private readonly repository: Repository<T>,
    ) { }
    async find(page: number = 1, pageSize: number = 10, relations?: string[], where?: FindOptionsWhere<T>) {
        const [data, total] = await this.repository.findAndCount({
            relations,
            where,
            skip: (page - 1) * pageSize,
            take: pageSize,
        });
        return {
            items: data,
            total: total
        }
    }
    async findOne(id: any): Promise<T> {
        return await this.repository.findOne( {where: { id } as FindOptionsWhere<T>});
    }
    async create(data: DeepPartial<T>): Promise<T> {
        const entity = await this.repository.create(data);
        return this.repository.save(entity);
    }
    // async update(data: any): Promise<any> {
    //     return await this.repository.update(data.id, data);
    // }
    // async update(id: number, data: DeepPartial<T>): Promise<T> {
    //     await this.repository.update(id, data);
    //     return await this.repository.findOne(id);
    //   }
    async delete(id: number): Promise<DeleteResult> {
        return await this.repository.delete(id);
    }
}